package com.zmx.b2c.pay.web;

import com.zmx.b2c.order.service.B2COrderService;
import com.zmx.b2c.pay.dto.PaymentDto;
import com.zmx.b2c.pay.service.PaymentService;
import com.zmx.common.common.web.AbstractController;
import com.zmx.common.common.web.rest.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Description: 支付控制器
 * @ClassName: PaymentController
 * @Author zhaomxr
 * @Date 2022-01-12 15:28
 */
@Api("支付")
@Slf4j
@RestController
public class PaymentController extends AbstractController<PaymentDto, PaymentService> {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private B2COrderService b2COrderService;

    @ApiOperation(value = "吊起支付", tags = "吊起支付")
    @PostMapping("/pay")
    public ResponseResult pay(@RequestParam(required = true) String orderSn) {
        Map<String, Integer> decrementMap = null;
        try {
            decrementMap = paymentService.toPay(orderSn);
            return ResponseResult.success();
        } catch (Exception e) {
            log.error("支付失败 ", e);
            // **********支付失败回写商品库存**********
            if (decrementMap != null && decrementMap.size() > 0) {
                for (String productId : decrementMap.keySet()) {
                    Integer quantity = decrementMap.get(productId);
                    redisTemplate.opsForValue().increment(productId, quantity);
                }
            }

            return ResponseResult.fail("支付失败");
        }
    }

    @ApiOperation(value = "回调支付", tags = "回调支付")
    @PostMapping("/callback/notify")
    public ResponseResult callback(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
        try {
            //解析微信支付回调参数
            //暂时先不写

            //回写订单及支付表
            String orderSn = "";
            paymentService.callback(orderSn);
            return ResponseResult.success();
        } catch (Exception e) {
            log.error("回调失败", e);
            return ResponseResult.fail("回调失败");
        }
    }

}
